exports.plugin = {
  name: 'answersModel',
  register: async (server) => {
    const { mongoose } = server;
    const schema = mongoose.Schema({
      paperId: String,
      outlines: Object,
      items: Object,
      ctime: {
        type: Date,
        default: Date.now,
      },
    });

    schema.methods = {
      // 获取答卷总数
      getAnswersCount(paperId) {
        return this.model('answers').find({ paperId }).countDocuments();
      },
      // 获取答卷
      getAnswers(paperId, {
        page, perPage,
      } = {
        page: 1,
        perPage: 10,
      }) {
        return this.model('answers').find({ paperId }, { __v: 0 })
          .skip((page - 1) * perPage)
          .limit(perPage)
          .sort({ ctime: -1 });
      },
      // 添加答卷
      addAnswers(data) {
        return this.model('answers').create(data);
      },
      // 根据ID获取单个答卷信息
      getAnswerById(_id) {
        return this.model('answers').findById(_id, { __v: 0 });
      },
      // 根据ID获取单个答卷信息
      deleteAnswerById(_id) {
        return this.model('answers').deleteOne({ _id });
      },
    };
    const Answers = mongoose.model('answers', schema);
    server.decorate('request', 'answersModel', new Answers());
  },
};
